package gestoremulte.pack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
/*
 * Questa classe è l'activity che si occupa di caricare le Notifiche e i verbali
 */
public class CaricaNotificaVerbaleActivity extends Activity {
    /** Called when the activity is first created. */
	
	private ListView lv;
	MyDatabase db = null;
	SimpleAdapter adapter; // questo adapter serve per creare una lista di verbali e notifiche
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.caricanotificaverbale);
        
        lv=(ListView)findViewById(R.id.VerbaliNotificheLW);
        
        db=new MyDatabase(this);
        db.open();
        
        
        
        final List<HashMap<String, String>> fillMaps = db.loadNotifiche_Verbali();        
        
        //si istanzia l'adapter e si carica la lista con gli elementi presi dal DB
        adapter = new SimpleAdapter(this, fillMaps, R.layout.elementcaricanotifica,
        		new String[] {"gender", "nverb", "data_ora"}, new int[]{R.id.Gender,R.id.Verbalenumber,R.id.data_oraVerbale});
        
        
        db.close();
        
        lv.setAdapter(adapter);
        
        lv.setClickable(true); 
        // si imposta il on click listner sulla lista: On itemLongClick è quando si tiene premuto a lungo su un elemento della lista
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				AlertDialog.Builder adb=new AlertDialog.Builder(CaricaNotificaVerbaleActivity.this);
		        adb.setTitle("Cancellazione");
		        adb.setMessage("Sei sicuro di voler cancellare l'elemento? "); // in questa parte si chiede una conferma della cancellazione della notifica-verbale
		        final int positionToRemove = arg2;
		        adb.setNegativeButton("Cancel", null);
		        adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
		        	@Override
		        	public void onClick(DialogInterface dialog, int which) {
		            	db.open();
						HashMap<String,String> o =(HashMap<String,String>) lv.getItemAtPosition(positionToRemove);
						if (o.get("gender").equals("Notifica")){
							String nverb = o.get("nverb");
							db.deleteNotifica(nverb);
							
						}
						
						else{
							String nverb = o.get("nverb");
							db.deleteVerbale(nverb);
						}
						db.close();
						fillMaps.remove((HashMap<String,String>) lv.getItemAtPosition(positionToRemove));
						adapter.notifyDataSetChanged();
						
		            }

					
					});
		        adb.show();
				
				return false;
			}

        }
        );
        // in questa parte si spiega cosa succede quando si clicca semplicemente su un item
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        	 
        	// Se è un vebrale si carica l'activity VerbaleActivity impostando il verbale nell'intent
        	// se è una Notifica si carica l'activity RiassuntoMultaActivity.
        	// i dati vengono presi dal DB.
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				db.open();
				HashMap<String,String> o =(HashMap<String,String>) lv.getItemAtPosition(arg2);
				
				if (o.get("gender").equals("Notifica")){
					String nverb = o.get("nverb");
					Notifica not = db.getNotifica(nverb);
					db.close();
					Intent i = new Intent(CaricaNotificaVerbaleActivity.this,RiassuntoMultaActivity.class);
	                i.putExtra("targa", not.getTarga());
	                i.putExtra("via", not.getVia_comune());          	
	            	i.putExtra("data_ora", not.getData_ora());
	            	i.putExtra("sanzione", not.getSanzione());
	            	ArrayList<String> in = not.getDescrizioneInfrazione();
	            	ArrayList<String> co = not.getInfrazioni();
	            	String infrazioni ="";
	            	for (int f=0; f< in.size();f++)
	            		infrazioni += co.get(f)+ "-" + " " + in.get(f) + "\n";
	            	
	            	
	            	i.putStringArrayListExtra("infraz", not.getDescrizioneInfrazione());
	            	i.putStringArrayListExtra("cod", not.getInfrazioni());
	            	i.putExtra("infrazioni", infrazioni);
	            	i.putExtra("nverbale", not.getVerbaleNumber());
	            	i.putExtra("lat", not.getLat());
	            	i.putExtra("lon", not.getLon());
	            	i.putExtra("fromDB", true);
	            	
	            	
	            	startActivity(i);
				}
				
				else{
					String nverb = o.get("nverb");
					Verbale v = db.getVerbale(nverb);
					
					db.close();
					Intent i = new Intent(CaricaNotificaVerbaleActivity.this,VerbaleActivity.class);
					i.putExtra("verbale",(Parcelable) v);
					i.putExtra("fromDB", true);
					
					
	            	startActivity(i);
				}
			}
        	});


        getWindow().setFormat(PixelFormat.RGBA_8888);   //visto che usiamo i gradient, usiamo questo trick
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);  
             
        lv.setBackgroundDrawable(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.BLUE,Color.parseColor("black")}));
   
        Animation a2 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        a2.setDuration(1000);
        a2.setInterpolator(AnimationUtils.loadInterpolator(this, android.R.anim.decelerate_interpolator));
        lv.startAnimation(a2);
        //entra da sopra
    }
    
    /*
     * Sezione dei metodi richiamati nelle diverse Activity per il Menu e il restart dell'app.
     * 
     */
    protected void onRestart(){
    	super.onRestart();
    	if (VariabiliCondiviseApplication.restored){
    		
    		TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            VariabiliCondiviseApplication.IMEI = telephonyManager.getDeviceId();
			VariabiliCondiviseApplication.online = false;
			
			CustomDialogLoginOffline dialog = new CustomDialogLoginOffline(this);
		    dialog.setCancelable(false);
		    dialog.show();
    	}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.icon: 
            	CustomDialogLoginOnline dialog = new CustomDialogLoginOnline(this);
            	dialog.show();
                break;
           
        }
        return true;
    }
    
    protected void onPause(){
    	super.onPause();
    	if (VariabiliCondiviseApplication.backClick)
    		VariabiliCondiviseApplication.restored = false;
    	else
    		VariabiliCondiviseApplication.restored = true;
    	VariabiliCondiviseApplication.backClick = false;
    }
 
 @Override
    public void onBackPressed() {
	 	super.onBackPressed();
    	VariabiliCondiviseApplication.backClick = true;
    	Log.e("PROVA", "OK");
    }
 
 
}
